﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using OT.Data;
using OT.Areas.Instructor.Models;
using PagedList;

namespace OT.Areas.Instructor.Controllers
{
    public class AttemptInstructorController : Controller
    {
        //
        // GET: /Instructor/AttemptInstructor/
        readonly OTEntitiesme OTDb = new OTEntitiesme();
        double TotalMarks = 0;
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public JsonResult Index(int pageNumber, int pageSize, string searchString, int pgindex)
        {
            List<AttemptInstructor> log = (from c in OTDb.AttemptMsts
                                  join top in OTDb.Tests
                                  on c.TestID equals top.TestID

                                  join us in OTDb.Users
                                  on c.UserID equals us.UserID
                                           select new AttemptInstructor
                                  {
                                      TestID = c.TestID,
                                      UserID = c.UserID,
                                      IsFinish = c.IsFinish,
                                      Score = (float)c.Score,
                                      AttemptID = (int)c.AttemptID,
                                      user = us.FirstName,
                                      TestName = top.TestName,
                                      CreatedDate = c.CreatedDate
                                  }).OrderBy(o => o.AttemptID).ToList<AttemptInstructor>();
            if (!string.IsNullOrEmpty(searchString))
                log = log.Where(r => r.user.ToLower().Contains(searchString.ToLower())).ToList();
            int recount =log.Count;
            log = log.Skip<AttemptInstructor>(pgindex * (pageNumber - 1))
                .Take<AttemptInstructor>(pgindex).ToList<AttemptInstructor>();
            return Json(new
            {
                PageNumber = pageNumber,
                PageSize = pageSize,
                PgIndex = pgindex,
                Data = log,
                RecordCount = recount
            });
        }
        public ActionResult Delete(int AttemptID)
        {
            AttemptInstructor err = null;
            try
            {
                var categry = OTDb.AttemptMsts.Where(r => r.AttemptID == AttemptID).SingleOrDefault();
                if (categry != null)
                {
                    err = new AttemptInstructor();
                    err.AttemptID = (int)categry.AttemptID;
                }
            }
            catch (Exception ex)
            {
                Utilities.InsertErrorLog(ex);
            }
            return PartialView(err);
        }
        [HttpPost]
        public string Delete(int AttemptID, string IsDelete)
        {
            string result = "";
            try
            {
                var City = OTDb.AttemptMsts.Where(r => r.AttemptID == AttemptID).SingleOrDefault();
                if (City != null)
                {
                    OTDb.AttemptMsts.Remove(City);
                    OTDb.SaveChanges();
                    result = "Success";
                }
            }
            catch (Exception ex)
            {
                Utilities.InsertErrorLog(ex);
            }
            return result;
        }
        [HttpPost]
        public string DeleteAll(string selectedRecord)
        {
            string result = "";
            string[] sep = { "," };
            string[] IDs = selectedRecord.Split(sep, StringSplitOptions.RemoveEmptyEntries);
            List<int> ids = new List<int>();

            foreach (var id in IDs)
                ids.Add(Convert.ToInt32(id));
            result = "";
            try
            {
                if (ids.Count != 0)
                {
                    foreach (int AttemptID in ids)
                    {
                        List<AttemptDtl> Attemptdtl = (from att in OTDb.AttemptDtls
                                                       where att.AttemptID.Value.Equals(AttemptID)
                                                       select att).ToList();
                        AttemptMst Attemptmst = OTDb.AttemptMsts.Where(r => r.AttemptID == AttemptID).FirstOrDefault();
                        foreach (AttemptDtl att in Attemptdtl)
                        {
                            OTDb.AttemptDtls.Remove(att);
                            OTDb.SaveChanges();
                        }
                        if (Attemptmst != null)
                        {
                            OTDb.AttemptMsts.Remove(Attemptmst);
                            OTDb.SaveChanges();
                        }
                    }
                    result = "Success";
                }
            }
            catch (Exception ex)
            {
                Utilities.InsertErrorLog(ex);
                result = "NotValid";
            }
            return result;
        }
        #region showdetail
        public ActionResult ShowDetail(int AttemptID)
        {
            TestResult trslt1 = new TestResult();
            trslt1.AttemptID = AttemptID;
            trslt1.PassingScore = OTDb.AttemptMsts.Where(a => a.AttemptID.Equals(AttemptID)).Select(t => t.Test.PassingScore.Value).FirstOrDefault();
            trslt1.TotalQuestion = OTDb.AttemptMsts.Where(a => a.AttemptID.Equals(AttemptID)).Select(t => t.Test.TotalQuestion.Value).FirstOrDefault();
            trslt1.PositiveMark = OTDb.AttemptMsts.Where(a => a.AttemptID.Equals(AttemptID)).Select(t => t.Test.PositiveMark.Value).FirstOrDefault();
            trslt1.NegativeMark = OTDb.AttemptMsts.Where(a => a.AttemptID.Equals(AttemptID)).Select(t => t.Test.NegativeMark.Value).FirstOrDefault();
            trslt1.TotalMarks = Convert.ToInt16(trslt1.TotalQuestion * trslt1.PositiveMark);
            trslt1.AttemptedQuestions = OTDb.AttemptDtls.Where(a => a.AttemptID.Value.Equals(AttemptID)).Count<AttemptDtl>();
            int SubjectID = OTDb.AttemptMsts.Where(a => a.AttemptID.Equals(AttemptID)).Select(t => t.Test.SubjectID.Value).FirstOrDefault();
            trslt1.SubjectName = OTDb.Subjects.Where(a => a.SubjectID.Equals(SubjectID)).ToString(); ;
            int TopicID = OTDb.AttemptMsts.Where(a => a.AttemptID.Equals(AttemptID)).Select(t => t.Test.TopicID.Value).FirstOrDefault();
            trslt1.SubjectName = OTDb.Topics.Where(a => a.TopicID.Equals(TopicID)).ToString();
            trslt1.UnAttemptedQuestions = Convert.ToInt16(trslt1.TotalQuestion - trslt1.AttemptedQuestions);
            trslt1.CorrectAnswers = OTDb.AttemptDtls.Where(a => a.AttemptID.Value.Equals(AttemptID) && a.IsRight == true).Count<AttemptDtl>();
            trslt1.WrongAnswers = OTDb.AttemptDtls.Where(a => a.AttemptID.Value.Equals(AttemptID) && a.IsRight == false).Count<AttemptDtl>();

            double totalPositiveMarks = Convert.ToDouble(trslt1.CorrectAnswers * trslt1.PositiveMark);
            double totalNegativeMarks = Convert.ToDouble(trslt1.WrongAnswers * trslt1.NegativeMark);
            trslt1.TotalScore = Convert.ToDouble(totalPositiveMarks - totalNegativeMarks);
            trslt1.Percantage = Convert.ToDouble((Math.Round((trslt1.TotalScore / trslt1.TotalMarks) * 100, 2)));
            trslt1.Result = (trslt1.Percantage >= trslt1.PassingScore) ? "Passed" : "Failed";
            ViewBag.PassingScore = trslt1.PassingScore;
            ViewBag.TotalQuestion = trslt1.TotalQuestion;
            ViewBag.TotalMarks = trslt1.TotalMarks;
            ViewBag.AttemptedQuestions = trslt1.AttemptedQuestions;
            ViewBag.UnAttemptedQuestions = trslt1.UnAttemptedQuestions;
            ViewBag.CorrectAnswers = trslt1.CorrectAnswers;
            ViewBag.WrongAnswers = trslt1.WrongAnswers;
            ViewBag.totalPositiveMarks = totalPositiveMarks;
            ViewBag.totalNegativeMarks = totalNegativeMarks;
            ViewBag.TotalScore = trslt1.TotalScore;
            if (trslt1.Percantage > 0)
            {
                ViewBag.Percantage = Math.Round(trslt1.Percantage, 2);
            }
            else
            {
                ViewBag.Percantage = "";
            }
            ViewBag.Result = trslt1.Result;
           


            int totque = 0;
            int mark = 0;
            var Attempts = (List<AttemptDetailInstructor>)null;
            try
            {
                Attempts = (from c in OTDb.AttemptDtls
                            where c.AttemptID.Value.Equals(AttemptID)
                            join top in OTDb.Questions
                        on c.QuestionID equals top.QuestionID
                            select new AttemptDetailInstructor
                            {
                                QuestionID = c.QuestionID.Value,
                                QuestionName = top.QuestionName,
                                AttemptID = c.AttemptID.Value,
                                YourAnswer = (byte?)c.YourAnswer.Value ?? 0,
                                YourAns = (c.YourAnswer.Value == 1) ? c.Question.Answer1 : (c.YourAnswer.Value == 2) ? c.Question.Answer2 : (c.YourAnswer.Value == 3) ? c.Question.Answer3 : (c.YourAnswer.Value == 4) ? c.Question.Answer4 : "No Answer Given",
                                CorrectAnswer = (byte?)c.CorrectAnswer.Value ?? 0,
                                CorreAns = (c.CorrectAnswer.Value == 1) ? c.Question.Answer1 : (c.CorrectAnswer.Value == 2) ? c.Question.Answer2 : (c.CorrectAnswer.Value == 3) ? c.Question.Answer3 : (c.CorrectAnswer.Value == 4) ? c.Question.Answer4 : "No Answer Given",
                                IsRight = (bool?)c.IsRight.Value ?? false,
                                Marks = (double?)c.Marks.Value ?? 0,
                            }).ToList();
                if (Attempts != null)
                {
                    foreach (AttemptDetailInstructor att in Attempts)
                    {
                        TotalMarks += att.Marks;
                    }
                }
                totque = (from t in OTDb.TestQuestions
                          where t.Test.AttemptMsts.FirstOrDefault().AttemptID.Equals(AttemptID)
                          select t).Count<TestQuestion>();
                mark = (from t in OTDb.Tests
                        where t.AttemptMsts.FirstOrDefault().AttemptID.Equals(AttemptID)
                        select t.PositiveMark).FirstOrDefault().Value;

                TempData["TotalMarks"] = TotalMarks.ToString();
                TempData["OutOf"] = (totque * mark).ToString();
            }
            catch (Exception ex)
            {
                Utilities.InsertErrorLog(ex);
            }
            return View(Attempts.ToPagedList(1, 300));
        }
        #endregion
    }
}
